<html>
<head>
  <link href="style.css" rel="stylesheet" type="text/css"/>
  <script src="jquery.js"></script>
  <script>
    var locale = chrome.i18n.getMessage; // Short-hand
    var GAMERCARD_LINK = "http://www.xboxlc.com/cards/newblack/{GT}.jpg";


    var waiting = false;

    var msg_body = "";

    var msg_waiting;

    function requestList(now){
        clearRows("list", 1);
        clearRows("msgList", 1);
        $("#list").append("<tr><th colspan='2'><img src='ajax-loader.gif'></img></td></tr>");
        $("#msgList").append("<tr><th colspan='3'><img src='ajax-loader.gif'></img></th></tr>");
        if(!now)
          now = false;
        chrome.extension.sendRequest({type: "friendsList",now:now}, function(response) {
          if(response.ok){
                responseRecieved(response);
          }
          else
              waiting = true;
        });
    }
    function clearRows(id, remaining){
        var elem = document.getElementById(id);
        while(elem.rows.length > remaining){
           elem.deleteRow(remaining);
        }
    }


    chrome.extension.onRequest.addListener(
        function(request, sender, sendResponse) {
            if(waiting && request.type=="waitingList"){
                responseRecieved(request);
                waiting = false;
                sendResponse();
            }
            else if(request.type == "msg"){
                console.log("Message " + request.status);
                if(request.status == "ready")
                {
                    if(msg_waiting)
                        sendResponse(msg_waiting);
                }
                else if(request.status == "sent")
                {
                    msg_waiting = null;
                    $("#msgForm_send")[0].disabled = false;
                    $("#msgForm_send").html(locale("msgForm_send"));
                    $("#msgFrame")[0].src = "about:blank";
                    $("#msgSentOK").fadeIn(10).fadeOut(1500);
                }
            }
            
    });
 
    function responseRecieved(data){
        document.getElementById("list").deleteRow(1);
        document.getElementById("msgList").deleteRow(1);
        $("#list").append(data.list);
        $("#msgList").append(data.msgList);
        refreshUI();
    }

    $(document).ready(function (){

      $("#plForm_sidebar").children().hide();

      // --Localization--
      $("a[id='myXboxLink']").html(locale("myXbox"));
      $("a[id='friendsLink']").html(locale("friends"));
      $("a[id='messagesLink']").html(locale("msgs"));
      $("a[id='msgBoxTabHead']").html(locale("sendmsg"));
      $("a[id='playerLookupTabHead']").html(locale("lookupPlayer"));

      $("#msgForm_toText").html(locale("msgForm_to"));
      $("#msgForm_send").html(locale("msgForm_send"));
      $("#msgForm_clear").html(locale("msgForm_clear"));

      $("#plForm_sidebar").children("a").first().text(locale("viewprofile"));
      $("#plForm_sidebar").children("a").eq(1).text(locale("sendmsg"));
      $("#plForm_gtLabel").text(locale("gTag") + ":");

      $("#list").html("<tr><th>" + locale("gTag") + "</th><th>" + locale("info_short") + "</th></tr>");
      $("#msgList").html("<tr><th colspan='2' >" + locale("gTag") + "</th><th>" + locale("msg") + "</th></tr>");
      
      if(localStorage["msgForm_to"])
         $("#msgForm_to")[0].value = localStorage["msgForm_to"];
      if(localStorage["msgForm_text"])
         $("#msgForm_text")[0].value = localStorage["msgForm_text"];

      refreshUI();
      requestList();
    });


    function refreshUI(){
        $("a").each(function (){
            if(this.href.indexOf("chrome.tabs") < 0 && this.href.indexOf("javascript:") < 0)
                this.href = "javascript:chrome.tabs.create({url:\"" + this.href + "\"})"
        });
        $("#list tr:odd").css("background-color", "#eeeeec");
	$("#msgList tr:nth-child(4n+2)").css("background-color", "#eeeeec");
    }

    function openMsg(id,obj){
        
        var msgBody = $(obj).parent().parent().next();
        if(msgBody.text().length <= 0){
            $(obj).parent().parent().find(".loadingMsg").toggle();
            var url = 'http://live.xbox.com/MessageCenter/Message' + '?msgId=' + id + '&' + Math.random();
            $.getJSON(url, function (data){
                msgBody.prev().find(".loadingMsg").toggle();
                $("#msgList").find(".msgBody:visible").toggle();
                msgBody.html("<td colspan='3'><hr>" + 
                            data.Message + 
                            "<br><a href='javascript:void(0);' onclick='msgForm_reply(this)' style='text-decoration:none;'><b>[" + 
                            locale("msg_reply") + "]</b></a> - " +
                            "<a href='javascript:void(0);' onclick='msg_delete(this)' style='text-decoration:none;'><b>[" +
                            locale("msg_delete") + "]</b><hr></td>");
                msgBody.toggle();
            });
        }
        else
          msgBody.toggle();
    }

    function toggleDisplay(show, sender){
        $(".tabHead a").not(sender).attr("class", "tabHeadNotSelected");
        $(sender).attr("class", "tabHeadSelected");
        $(".tableCont div:visible").not($("#" + show).parent()).slideToggle();
        $(".tableCont div:hidden").filter($("#" + show).parent()).slideToggle();

        switch($(sender).attr("id"))
        {
            case "playerLookupTabHead":
                $("#plForm_player")[0].focus();
                $("#plForm_player")[0].select();
                break;
            case "msgBoxTabHead":
                $("#msgForm_to")[0].focus();
                $("#msgForm_to")[0].select();
                break;
        }
    }

    function onlineOver(obj){
      obj = $(obj);
      var temp = obj.attr("title");
      obj.attr("title", obj.text());
      obj.html(temp);
    }
    function onlineOut(obj){
      onlineOver(obj);
    }
    var closeOnClick = true;
    function gamertagClick(obj,status){
        var parentClass = $(obj).parent().parent().attr("class");

        
        var online;
        if(parentClass.indexOf("Message") > 0){
            if(status.length == 0){
                $.get("http://xboxapi.duncanmackenzie.net/gamertag.ashx?GamerTag=" + escape($(obj).text()), function(data, textstatus){
                    var online = false;
                    if($(data).find("Valid").text() == "false"){
                        $("#plForm_result").html("<div>Error: Invalid</div>");
                        online = false;
                    }
                    else
                        online = $(data).find("Online").text() == "true";
                    gamertagClick(obj, online);
                });
                return;
            }
            online = status;
        }           
        else
           online = parentClass.indexOf("Online") > 0;
        $("#overlay").html("<span>" +
                                $(obj).text() + " - " +
                                "<span style='color:" + (online ? "#4e9a06" : "#a40000") + "'>" +
                                    (online ? "ONLINE" : "OFFLINE") + 
                                "</span>" +
                           "</span><br>" +
                           "<a href='javascript:void(0);' onclick=\"$('#overlay').hide(); msgForm_newMessage('" + $(obj).text() +  "');\">" +
                                locale("sendmsg") +
                           "</a> - " +
                           "<a href='http://live.xbox.com/profile/profile.aspx?GamerTag=" + escape($(obj).text()) + "'>" +
                                locale("viewprofile") +
                           "</a><br>" +
                           "<img style='padding-top:2px;' src='" + GAMERCARD_LINK.replace("{GT}", escape($(obj).text())) +  "'></img>")
        .show();
        refreshUI();
        return false;
    }
    function bodyClick(){
        if(closeOnClick)
            $("#overlay").hide();
    }

    function msg_delete(el){
        var id = $(el).parent().parent().prev().find(".msg_idCont").text(); 
        var url = "http://live.xbox.com/en-US/MessageCenter/Delete";
        $(el).parent().parent().prev().find(".loadingMsg").toggle();
        $.post(url, {"msgId":id}, function(){
            var i = id;
            console.log(i);
            var el = $(".msg_idCont:contains('" + i + "')")[0];
            console.log(el);
            $(el).parent().parent().next().detach();
            $(el).parent().parent().detach();
            chrome.extension.sendRequest({type:"deleteMessage",id:i});
        });
        
    }
    function msgForm_change(){
        var area = $("#msgForm_text")[0];
        localStorage["msgForm_to"] = $("#msgForm_to")[0].value;
        localStorage["msgForm_text"] = area.value;
        $("#msgForm_chars").html(area.value.length+"/250");
        if($("#msgForm_to")[0].value.length > 0)
            $("#msgForm_to").css({"backgroundColor":"#8ae234"});
        else
        {
            $("#msgForm_to").css({"backgroundColor":"#ef2929"});
            return false;
        }
        if(area.value.length <= 250){
            $("#msgForm_chars").css({"color":"#4e9a06"});
            return true;
        }
        else
        {
            $("#msgForm_chars").css({"color":"#a40000"});
            return false;
        }
    }
    function msgForm_submit(){
        var text = $("#msgForm_text")[0].value;
        var to = $("#msgForm_to")[0].value.split(",");
        if(to.length > 0)
            $("#msgForm_to").css({"backgroundColor":"#8ae234"});
        else
        {
            $("#msgForm_to").css({"backgroundColor":"#ef2929"});
            return false;
        }
        if(text > 250){
            $("#msgForm_chars").css({"color":"#a40000"});
            $("#msgForm_chars").html(locale("msgForm_tooMany"));
            return false;
        }

        msg_body = escape(text);

        msg_waiting = {Recipients:to, Message:text};

        $("#msgForm_send")[0].value = locale("msgForm_sending");
        $("#msgForm_send")[0].disabled = true;
    
        $("#msgFrame")[0].src = "http://live.xbox.com/MessageCenter/Compose?random=1";
    }
    function msgForm_reply(el){
        var to = $(el).parent().parent().prev().find("td").eq(1).text();
        var re = $(el).parent().parent().prev().find("td").eq(2).text();
        $("#msgForm_to")[0].value = to;
        $("#msgForm_text")[0].value = "RE: " + re + "\n";
        toggleDisplay('msgBox', $("#msgBoxTabHead")[0]);
        $("#msgForm_text")[0].focus();
        $("#msgForm_text")[0].select();
    }
    function msgForm_newMessage(gamertag){
        $("#msgForm_to")[0].value = gamertag;
        $("#msgForm_text")[0].value = "";
        toggleDisplay('msgBox', $("#msgBoxTabHead")[0]);
        $("#msgForm_text")[0].focus();
        $("#msgForm_text")[0].select();
    }
    function msgForm_closeTab(id){
        chrome.tabs.update(id, {selected:false}, function(tab){
            console.log(tab.status);
            if(tab.status == "complete"){
                $("#msgForm_send")[0].disabled = false;
                $("#msgForm_send").html(locale("msgForm_send"));
                chrome.tabs.remove(this.args[0]);
            }
            else{
                var text = $("#msgForm_send").html();
                $("#msgForm_send").html((locale("msgForm_sending").length == text.length+3) ? locale("msgForm_sending") : text + ".");
                var t = setTimeout("msgForm_closeTab(" + this.args[0] + ")", 500);
            }
        });
    }  
    function msgForm_clear(){
        $("#msgForm_to")[0].value = "";
        $("#msgForm_text")[0].value = "";
        msgForm_change();
    }

    function lookupPlayer(gamertag){
        $("#plForm_loadImg").show();
        $("#plForm_sidebar").children().show();
        $("#plForm_gamercard").html("<img src='" + GAMERCARD_LINK.replace("{GT}", escape(gamertag)) + "'></img><br>");
        $("#plForm_sidebar").children("a").first().attr("href", "http://live.xbox.com/profile/profile.aspx?GamerTag=" + escape(gamertag));
        $("#plForm_sidebar").children("a").eq(1).attr("href", "javascript:msgForm_newMessage('" + gamertag +  "');");
        refreshUI();
        $.get("http://xboxapi.duncanmackenzie.net/gamertag.ashx?GamerTag=" + escape(gamertag), function(data, textstatus){
            $("#plForm_loadImg").hide();
            if($(data).find("Valid").text() == "false"){
                $("#plForm_result").html("<div>Error: Invalid</div>");
                return;
            }
            var online = $(data).find("Online").text() == "true";
            $("#plForm_onlinestatus").text(online ? "ONLINE" : "OFFLINE").css("color", (online ? "#4e9a06" : "#a40000"));
            $("#plForm_result").html($(data).find("Info").text() + 
                                     ($(data).find("Info2").text().length > 0 ? "<br>" + $(data).find("Info2").text() : "") + 
                                     ($(data).find("Bio").text().length > 0 ? "<br>Bio:<p style='margin-top:0.5em; font-size:smaller; white-space:normal;'>" + $(data).find("Bio").text() + "</p>" : ""));
        });
    }
  </script>
</head>
<body onclick="bodyClick();" width="540px">
<div id="drop" style="display:none;visibility:hidden;"></div>
<div id="content">
    <div align="center" id="topLinks" style="padding-bottom: 2px;"><a href="http://live.xbox.com/default.aspx" id="myXboxLink">My Xbox</a> - <a id="friendsLink" href="http://live.xbox.com/profile/Friends.aspx">Friends</a> - <a id="messagesLink" href="http://live.xbox.com/profile/MessageCenter/ViewMessages.aspx">Messages</a></div>
    <div>
        <div class="tabHead">
            <a href='javascript:;' id="friendsLink" class="tabHeadSelected" onclick="toggleDisplay('list', this);">Friends</a>
            <a href='javascript:;' id="messagesLink" class="tabHeadNotSelected" onclick="toggleDisplay('msgList', this);">Messages</a>
            <a href='javascript:;' id="msgBoxTabHead" class="tabHeadNotSelected" onclick="toggleDisplay('msgBox', this);">Send Message</a>
            <a href='javascript:;' id="playerLookupTabHead" class="tabHeadNotSelected" onclick="toggleDisplay('playerLookup', this);">Lookup Player</a> 
        </div>
        <div class="tableCont">
            <div id="overlay" style="display:none;"  onmouseout="closeOnClick=true;" onmouseover="closeOnClick=false"></div>
            <div>
                <table id="list"></table>
            </div>
            <div style="display:none;">
                <table id="msgList"></table>
            </div>
            <div style="display:none;">
                <table id="msgBox">
                    <tr><th width="25%"><span id="msgForm_toText">To</span>:</th><th width="75%" style="text-align:left;"><input id="msgForm_to" onchange="return msgForm_change();" onkeypress="if(event.which == 13) $('#msgForm_text')[0].focus();"/></th></tr>
                    <tr><td colspan="2"><textarea rows="8" cols="32" id="msgForm_text" onkeyup="return msgForm_change();" onchange="return msgForm_change();"></textarea></td></tr>
                    <tr><td style="text-align:right"><span id="msgForm_chars">0/250</span></td><td><button id="msgForm_send" onclick="msgForm_submit();">Send</button><button id="msgForm_clear" onclick="msgForm_clear();">Clear</button><span id="msgSentOK" style="display:none;">OK!</span></td></tr>
                </table>
            </div>
            <div style="display:none;">
                <table id="playerLookup">
                    <tr><th id="plForm_gtLabel">Player:</th><th><input id="plForm_player" onkeypress="if(event.which == 13) $(this).next().click();"/><button onclick="lookupPlayer($('#plForm_player')[0].value);">GO!</button><img id="plForm_loadImg" src="ajax-loader-kit.gif" style="display:none;"/></th></tr>
                    <tr>
                        <td width="200" height="136" id="plForm_gamercard"></td>
                        <td id="plForm_sidebar">
                                <span id="plForm_onlinestatus">STATUS</span><br>
                                <a href="">Profile</a><br>
                                <a href="">Send Message</a>
                        </td>
                    </tr>
                    <tr><td colspan="2" id="plForm_result"></td></tr>
                </table>
            </div>
        </div>
    </div>
</div>
<iframe id="msgFrame" style="display:none;"></iframe>
</body>
</html>
